<template>
    <MenuPage 
        ref="selectTable"
        :data="videoList" 
        :columns="columns"
        :page.sync="videoPage"
        :size.sync="videoPageSize"
        :total="videoTotal"
        showSelectTag
        selectName="originName"
        :disabled="(item) => item.visibility === 'system' || item.hidden == 1 || (item.creator !== USER_ID && !isRootDesinger)"
        :selection.sync="selectVideoList"
        @queryFun="getFileList">
        <template slot="search">
            <Button type="primary" ghost icon="ios-cloud-upload-outline" @click="showModalBtn">上传视频</Button>
            <Button type="error" ghost icon="ios-trash-outline" @click="delLists" style="margin-left:  5px;">批量删除</Button>
            <Divider type="vertical" style="margin: 10px 0px 10px 10px;"/>
                      <div style="height: 32px;line-height: 32px;margin:0 15px">
                <Checkbox v-model="uploadByMe" @on-change="searchUploadByMe" style="width: 70px;">由我创建</Checkbox>
            </div>
            <!-- <i-select clearable v-model="selectFileType"  placeholder="文件类型" style="width: 150px;margin-left: 15px" @on-change="selectFileTypeChange">
                <i-option value="image">图片</i-option>
                <i-option value="video">视频</i-option>
                <i-option value="docs">文档</i-option>
                <i-option value="audios">音频</i-option>
                <i-option value="relay">glb</i-option>
                <i-option value="files">其他</i-option>
            </i-select> -->
            <i-select clearable placeholder="可见范围" style="width: 150px;margin-left: 15px " v-model="ispublic" @on-change="getFileList">
                <i-option value="range">平台</i-option>
                <i-option value="system">系统</i-option>
                <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
            </i-select>
            <Input v-model.trim="fileInput"  placeholder="文件名称" clearable @on-change="searchFile" style="width: 180px;margin-left: 15px;"/>
            <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshFile()"><i class="el-icon-refresh-right" /></Button>
        </template>
        <Modal v-model="pdfModal"
            	title="pdf预览"
            	width="60"
            	:mask-closable = "false"
            	footer-hide
            	>
              <!--<iframe src="http://172.18.100.4:18769/api/viewer/document/F495148a-a7ca-49a3-8035-d83c752a90f1" width="100%" height="600px" ></iframe>-->
              <iframe :src="pdfUrl" width="100%" height="600px" scrolling="none" frameborder="0"></iframe>
        </Modal>
        <!--上传视频-->
        <Modal
            v-model="uploadFileModal"
            :mask-closable="false"
            width="500"
            :closable = 'false'
            :footer-hide="true"
            title="上传视频">
            <!-- <div class="uploadTypeWrap">
                支持上传类型：<Tooltip :content="formatStr" placement="top-start" width="200">
                    <Icon type='ios-help-circle' color='rgb(255, 153, 0)' />
                </Tooltip>
               <p>文件名称:只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符</p>
            </div> -->
            <Form ref="formItem" :model="formItem" :rules="formItemRule" :label-width="80">
                <FormItem label="可见范围" prop="visibility">
                    <RadioGroup v-model="formItem.visibility">
                        <Radio label="company">单位</Radio>
                        <Radio label="person">个人</Radio>
                    </RadioGroup>
                </FormItem>
                <FormItem label="上传视频" prop="file">
                    <Upload
                            ref='uploadFile' :action="upLoadUrl" :before-upload="handleUploadIcon">
                        <Button icon="ios-cloud-upload-outline" :disabled="!!loading">选择文件</Button>
                    </Upload>
                    <Poptip class="too" popper-class="tooltipclass" theme="dark" placement="top" width="400" :transfer='true' trigger="hover">
                        <Icon type="ios-alert" class="ios-alert" />
                            <div class="api" slot="content">
                                <p style="white-space: normal;word-break: break-all;">支持上传类型:{{formatStr}}</p>
                                <p style="white-space: normal;">文件名称:只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符</p>
                            </div>
                    </Poptip>
                    <div v-if="formItem.file !== null">
                        <p>文件名: {{ formItem.file.name}}</p>
                        <p>大小：<span v-text="fileSize"></span></p>
                        <template v-if="progress>0">
                          <Progress :percent="progress"></Progress>
                          <p v-if="speed">速度：<span v-text="speed"></span></p>
                        </template>
                    </div>
                </FormItem>
                <!--<FormItem label="图片类型" prop="bucket" v-if="showSelectBucket">
                    <RadioGroup v-model="formItem.bucket">
                        <Radio label="exp-img">课件图片</Radio>
                        <Radio label="course-img">课程图片</Radio>
                        <Radio label="guideImg">指导书图片</Radio>
                        <Radio label="images">其他</Radio>
                    </RadioGroup>
                </FormItem>-->
                <FormItem>
                    <Button type="primary" @click="formBtn('formItem')" :loading="!!loading">确定</Button>
                    <Button @click="cancelUpload()" style="margin-left: 8px">取消</Button>
                </FormItem>
            </Form>
        </Modal>
        <Modal v-model="uploadShow"
            	title="关闭提示"
            	width="300"
            	:mask-closable = "false"
                :closable = 'false'
                @on-ok="YesOk"
                @on-cancel="NoCancel"
            	>
                <p>关闭对话框，可能导致上传失败，是否关闭？</p>
        </Modal>
    </MenuPage>
</template>
<script>
    function getSize(val) {
        let type = ''
        if(val > (1024*1024)){
            val = val/(1024*1024)
            type = ' MB'
        }else{
            val = val/1024
            type = ' KB'
        }
        val = val.toFixed(2)
        return val+''+type
    }
    import {Modal} from 'iview'
    import $ from 'jquery'
    import cookieUse from '@/libs/cookie.js'
    import encryption from '@/libs/encryption.js'
    import {getFilesData,delFile} from '@/api/uploadFile.js'
    import {
		debounce
	} from '@/libs/utils'
    export default {
        components:{},
        data () {
            const validateUpload = (rule, value, callback) => {
                if (this.formItemRule.file === null) {
                    callback(new Error('Please select the file to upload'))
                } else {
                    callback()
                }
            }
            return {
                // 用户信息
                uptedIdx:0,// 上传文件几片了
                USER_ID:'',
                isRootDesinger:'',
                // 页面设置
                fullHeight: document.documentElement.clientHeight,
                fullWidth: document.documentElement.clientWidth,
                contentHei:'auto',
                // 显示
                showDataList:true,
                showDefImg:false,
                // 过滤
                uploadByMe:false,
                // 文件列表
                videoPage:1,
                videoPageSize:12,
                videoList:[],
                selectVideoList:[],
                columns : [
                    {
                        type:'selection',
                        width:60
                    },
                    {
                        title: '文件名',
                        key: 'originName',
                        minWidth:100,
                        tooltip:true
                    },
                    // {
                    //     title: '文件类型',
                    //     key: 'bucket',
                    //     filter:this.filterFileType
                    // },
                    {
                        title: '可见范围',
                        key: 'visibility',
                        minWidth:100,
                        render:(h,params) => {
                        return h('span',{
                            style:{
                            color:this.setVisibility(params.row.visibility).color
                            }
                        },this.setVisibility(params.row.visibility).text)
                        }
                    },
                    {
                        title: '文件大小',
                        key: 'size',
                        filter:this.getSize,
                        minWidth:100,
                        tooltip:true
                    },
                    {
                        title: '时长',
                        key: 'time',
                        filter:(time,item) => {
                            return this.getTimes(item)
                        },
                        minWidth:100,
                        tooltip:true
                    },
                    {
                        title: '创建时间',
                        key: 'created'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        opList:[
                            {
                            txt:'下载',
                            type:'download',
                            on:{
                                click:(data,e) => {
                                this.downInfo(data)
                                }
                            }
                            },
                            {
                            txt:'查看',
                            type:'check',
                            disabled:(data) => {
                                return this.isDisabledType(data.bucket,data.originName)
                            },
                            on:{
                                click:(data,e) => {
                                this.checkInfo(data)
                                }
                            }
                            },
                            {
                            txt: '删除',
                            tooltip: true,
                            type: 'delete',
                            title: '确定要删除这个文件吗？',
                            disabled: (data) => {
                                return this.setIsClick(data) ? true :false
                            },
                            on: {
                                click: (data,e) => {
                                this.deleteVideo(data)
                                }
                            }
                            }
                        ]
                    },
                ],
                videoTotal:0,
                // 搜索 图片视频
                fileInput:'',
                selectFileType:'video',
                searchFileType:'',
                // 上传路径
                upLoadUrl:`${this.baseURL}/minio/upload/merge/file`,
                setUpLoadHead:{'Authorization':cookieUse.getCookie('desig-token')},
                progressPercent:0,
                showProgress:false,
                // 上传
                uploadFileModal:false,
                formItem:{
                    visibility:'company',
                    file:null,
                    bucket:''
                },
                formItemRule:{
                    visibility: [
                        { required: true, message: 'Please select ispublic', trigger: 'change' }
                    ],
                    file: [
                        { required: true, validator: validateUpload, trigger: 'change' }
                    ],
                    bucket:[
                    	{ required: true, message: 'Please select ispublic', trigger: 'change' }
                    ]
                },
                ispublic:'',
                formatStr:'',
                formatArr: ['mp4','avi','flv'],
                // formatArr:[
                //     'xz', 'bin', 'dmp', 'dms', 'rmvb', 'midi', 'exe', 'xml', 'jar', 'qxd', 'wks', 'ram', 'zip', 'rar', 'apr', 'ac', '7z', 'mpg', 'lnk',
                //     'png', 'eps', 'ott', 'ra', '123', 'au', 'dwg', 'aw', 'doc', 'odp', 'rm', 'odt', 'nsf', 'aac', 'lwp','log', 'vsd', 'flac', 'dot', 'mid', 'wma',
                //     'mif', 'cmx', 'wmf', 'arc', 'vcd', 'epub', 'pgm', 'vcf', 'kmz', 'jpeg', '3gp', 'mar', 'xlsx', 'ntf', 'wmv', 'fli', 'wmz', 'rtf', 'fdf', 'docx',
                //     'xpi', 'flv', 'pps', 'asf', 'ppt', 'kwd', 'cod', 'xps', 'com', 'msf', 'msi', 'swf', 'iso', 'bmp', 'asx', 'oga', 'hqx', 'ogg', 'p10', 'rmi',
                //     'tif', 'ico', 'mkv', 'sxd', 'sxc', 'ogv', 'prc', 'ogx', 'sxi', 'cpt', 'xar', 'spf', 'chm', 'wpd', 'mdb', 'webp', 'adp', 'webm', 'gpx', 'spl',
                //     'pptx', 'sxw', 'mdi', 'wps', 'psd', 'tiff', 'eml', 'aiff', 'cab', 'gif', 'mmf', 'fm', 'vob', 'caf', 'rgb', 'cap', 'dtd', 'avi', 'cat', 'sil', 'm4a',
                //     'bz2', 'class', 'jpe', 'sit', 'jpg', 'pcx', 'dll', 'org', 'ttf', 'xla', 'hlp', 'wav', 'm4v', 'pdb', 'wri', 'mp4', 'mp3', 'pdf', 'obj', 'pls', 'csh',
                //     'mny', 'pub', 'xls', 'dmg','glb','txt','json','md'
                // ],
//              formatArr:["jpeg","jpg","jpe","png","gif","tiff","bmp","dwg","psd","ico","rgb","ogx","pcx","mdi","tif","pgm","cmx","webp","pdf","doc","docx","xls","xlsx",
//              	"xla","pptx","pps","ppt","rtf","zip","bz2","7z","cab","rar","epub","mp4","webm","ogv","ogg","3gp","3g2","m4v","mpg","vob","fli","mkv","asf","asx","wmv",
//              	"flv","avi","m4a","sil","ra","ram","au","wma","aiff","mp3","mid","midi","rmi","oga","wav","caf","flac","adp","aac"],
                speed:0,
                loaded:0,
                fileSize:0,
                progress:0,
                loading:false,
                downLoadImg:require('../../assets/project/download-h.png'),
                checkIcon:require('../../assets/project/magnifier-h.png'),
                checkIconDisabled: require('../../assets/project/magnifier-s.png'),
                pdfUrl:'',
                pdfModal:false,
                showSelectBucket:false, //是否需要选择桶
                uploadShow:false,//上次时关闭对话框提示
                updataLoading:true,
                isUpdataing:false//判断是否在上传中
            }
        },
        created(){
            // 获取用户id
            let November = sessionStorage.getItem('November')
            November = JSON.parse(encryption.SelfUseDecrypt(November))
            this.USER_ID = November.userId
            this.isRootDesinger = November.isRootDesinger


          
        },
        mounted(){
            // 列表
            this.getFileList()
            this.formatStr = this.formatArr.toString()
        },
        methods:{
            delLists() {
                let ids = this.selectVideoList.map(item => item.id)
                if(!ids.length) {
                    this.$Message.warning('请选择需要删除的数据')
                    return false
                }
                this.$Modal.confirm({
                    title: '删除',
                    content: '是否确认删除？',
                    onOk: () => {
                        this.$Spin.show({
                            render: (h) => {
                                return h('div', [
                                h('Icon', {
                                    'class': 'demo-spin-icon-load',
                                    props: {
                                        type: 'ios-loading',
                                        size: 18
                                    }
                                }),
                                h('div', '删除中...')
                                ])
                            }
                        });
                        const allApi = []
                        ids.forEach(item => {
                            const oneApi = delFile(item)
                            allApi.push(oneApi)
                        })
                        Promise.all(allApi).then(res => {
                        let errorMessage = []
                        res.forEach(ele => {
                            if(ele.data.code != 1) {
                            errorMessage.push(ele.data.message)
                            }
                        })
                        let uptedIdx = res.every(value => { return value.data.code == 1})
                        if(uptedIdx) {
                            this.$Spin.hide();
                            this.$Message.success('删除成功')
                            if(this.videoPage > 1 && ids.length == this.videoList.length) {
                                this.videoPage --
                            }
                            this.getFileList()
                            this.selectVideoList = [];
                        }else {
                            this.getFileList()
                            this.$Spin.hide();
                            this.$Message.error(errorMessage[0])
                        }
                        
                        })
                    },
                    onCancel: () => {}
                });
            },
            // 设置高度
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.contentHei =   this.fullHeight - 197  // 80是头部高度  60是上下padding
                this.videoPageSize = Math.floor(this.contentHei/96)
            },
            // 文件列表
            getFileList(){
                this.showDefImg = true
                this.showDataList = false
                let params = {
                    pageIndex:this.videoPage,
                    pageSize:this.videoPageSize,
                }
                let data = {
//              	originName:this.fileInput,
//                  type:this.searchFileType,
//                  sortBy:'File_Time',
//                  order:'desc',
//                  visibility : this.ispublic
                }
                if(this.uploadByMe){
                    // params.isPublic = 0
                    data.creator = this.USER_ID
                }
                if(this.fileInput){
                	data.originName = this.fileInput
                }
                // if(this.searchFileType){
                // 	data.bucket = this.searchFileType
                // }
                if(this.ispublic){
                	data.visibility = this.ispublic
                }
                data.bucket = 'videos'
                getFilesData(params,data)
                    .then(res=>{
                        if(res.data.code == 1){
                            let attribute = res.data.data;
                            let items = attribute.list;
                            this.videoTotal = attribute.total;
                            this.videoList = items
                            this.videoList.forEach(ele => {
                                if(ele._checked) {
                                    ids.push(ele.guidbookid)
                                }
                            })
                            if(items.length > 0){
                                this.showDefImg = false
                                this.showDataList = true
                            }else {
                                this.showDefImg = true
                                this.showDataList = false
                            }
                        }else{
                            this.showDefImg = true
                            this.showDataList = false
                        }
                    })
                    .catch(err=>{
                        this.showDefImg = true
                        this.showDataList = false
                        console.log(err)
                    })
            },
            videoOnChange(val){
                this.videoPage = val;
                this.getFileList();
            },
            confirmEnding(str, target) {
                 var start = str.length-target.length;
                 var arr = str.substr(start,target.length);
                 if(arr == target){
                 return true;
                 }
                 return false;
            },
            isDisabledType(type, name) {
                let list = name.split('.')
                let lastStr = list.pop().trim().toLowerCase()
                if (list.length < 1) { // 没有后缀名需要禁用
                    return true
                } else {
                    let othersArr = ["zip","bz2","7z","cab","rar","epub"]; // 需要被禁用的类型
                    return othersArr.includes(lastStr)
                }
            },
            checkInfo(params){
                if (this.isDisabledType(params.bucket, params.originName)) { // 这两种类型不支持预览，不需要打开预览页面
                    return
                }
                let path = params.path;
				if(params.originName.endsWith('.md')){
					let href = this.$router.resolve({
						name:'mdPreview',
						query:{
							path:path,
							name:params.originName
						}
					}).href;
					window.openTrain(href,'_blank')
				}else{		
					window.openTrain(`/api/minio/filePreview?path=${path}`);
				}
                // let fileId = params.id;
                // let path = params.path;
                // window.openTrain(`/api/minio/filePreview?path=${path}`);
                return
                if(params.fileCatalog == 'docs'){
                  let fileName = params.fileName;
                  if(this.confirmEnding(fileName,'pdf')){
                    //pdf文档用直接展示
                    window.openTrain(`/Learn/${path}`);
                  }else{
                    //word文档转pdf展示
                    let reviewUrl = `/api/minio/viewer/document/${fileId}`; //ftp/edu-ftp/viewOnline/pdf/${fileId}
                    this.pdfUrl = `static/pdfjs/web/viewer.html?file=${encodeURIComponent(reviewUrl)}`
                    this.pdfModal = true;
                  }
                }else if( params.fileCatalog == 'files'){ 
                    //压缩文档下载
                    window.openTrain(`/api/ftp/edu-ftp/download?id=${fileId}`);
                }else {
                   //其他展示
                   // window.openTrain(`/Learn/${path}`);
                   window.openTrain(`/api/minio/filePreview?path=${path}`);
                }
            },
            downInfo(params){
                let fileId = params.id;
                let path = params.path;
                window.openTrain(`/api/minio/download/${fileId}`);
            },
            searchFile(val){
                this.videoPage = 1
                this.fileInput = this.fileInput
                this.getFileList();
            },
            selectFileTypeChange(val){
                this.videoPage = 1
                if(!val){
                    this.searchFileType = '';
                }else if(val == 'image'){
                    this.searchFileType = 'images';
                }else if(val == 'video'){
                    this.searchFileType = 'videos';
                }else if(val == 'docs'){
                    this.searchFileType = 'docs';
                }else if(val == 'audios'){
                    this.searchFileType = 'audios';
                }else if(val == 'files'){
                    this.searchFileType = 'files';
                }else if(val == 'relay'){
                	this.searchFileType = 'relay';
                }
                this.getFileList();
            },
            searchUploadByMe(val){
                this.videoPage = 1
                this.getFileList()
            },
            refreshFile(){
                this.videoPage = 1
                this.fileInput = ''
                this.ispublic = ''
                this.selectFileType = 'video'
                this.searchFileType = ''
                this.uploadByMe = false
                this.selectVideoList = [];
                this.getFileList()
            },
            // 删除
            deleteVideo(params){
                if(params.visibility === 'public' || params.hidden == 1 || (params.creator !== this.USER_ID && !this.isRootDesinger)){
                    this.$Message.info({
                        content:'没有权限！',
                        duration:3,
                    })
                    return false
                }
                let fileId = params.id;
                delFile(fileId)
                    .then(res=>{
                        if(res.data.code == 1){
                            this.$Message.success({
                                content:'删除成功！',
                                duration:3
                            });
                            this.getFileList();
                            this.$refs.selectTable.closeItem(params);
                        }else {
                            this.$Message.error('删除失败！');
                        }
                    })
                    .catch(err=>{
                        console.log(err)
                    })
            },
            // 上传成功
            upLoadSuccess(response, file, fileList){
                if(response.code == 1){
                    this.showProgress = false;
                    this.$Message.success('上传成功');
                    this.getFileList();
                }else{
                    this.showProgress = false;
                    this.$Message.error({
                        content:response.message,
                        duration:3,
                    });
                }
            },
            // 上传失败
            upLoadErr(error, file, fileList){
                this.$Message.error('上传失败');
            },
            // 视频上传时的钩子
            upLoadProgress(event, file, fileList){
                let percent = event.percent;
                percent = percent.toFixed(1);
                this.progressPercent = parseInt(percent);
            },
            // 上传前
            beforeUpload(file){
                if(file){
                    this.showProgress = true;
                }
            },

            // 上传视频 2020/03/27 新
            showModalBtn(){
                this.uploadFileModal = true
                this.loading = false
                this.formItem.visibility = 'share'
                this.formItem.file = null
                this.showSelectBucket = false
                this.speed = 0
                this.loaded = 0
                this.fileSize = 0
                this.progress = 0
                this.uptedIdx = 0
            },
	        getFileName (name) {
		        return name.substring(0, name.lastIndexOf("."))
	        },
          handleUploadIcon(file){
            	this.speed = 0;
                this.loaded = 0;
                this.progress = 0;
                this.isUpdataing = true
                this.onlyFileName = file.name + '_' + new Date().getTime();
                if (file) {
                    if (file.size > 1024 * 1024) {
                        this.fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
                    } else {
                        this.fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB'
                    }
                    //验证名称
			      	if(file.name){
				        let name = this.getFileName(file.name);
			      		let reg = new RegExp("^[\u4E00-\u9FA5a-zA-Z0-9_ -]*$");
			      		if (!reg.test(name) || name.length > 64) {
			      			this.$Message.error({
		                        content:'文件名称只能包含中文、英文、数字、下划线、-，名称长度为1-64个字符',
		                        duration:3,
		                   })
			      		   return false;
			      		}
			      	}
                }
                let exceededNum=file.name.lastIndexOf(".");
　　            			let exceededStr=file.name.substring(exceededNum+1,file.name.length).trim().toLowerCase();
                if(exceededStr && this.formatArr.indexOf(exceededStr)>-1){
                    this.formItem.file = file;
                    let imageArr = ["jpeg","jpg","jpe","png","gif","tiff","bmp","dwg","psd","ico","rgb","ogx","pcx","mdi","tif","pgm","cmx","webp"];
                    let docsArr = ["pdf","doc","docx","xls","xlsx","xla","pptx","pps","ppt","rtf","txt","md"];
                    let othersArr = ["zip","bz2","7z","cab","rar","epub"];
                    let videoArr = ["mp4","webm","ogv","ogg","3gp","3g2","m4v","mpg","vob","fli","mkv","asf","asx","wmv","flv","avi"];
                    let audioArr = ["m4a","sil","ra","ram","au","wma","aiff","mp3","mid","midi","rmi","oga","wav","caf","flac","adp","aac"];
                    this.showSelectBucket = false;
                    if(imageArr.includes(exceededStr)){
                    	this.showSelectBucket = true;
                    	this.formItem.bucket = 'images';
                    	this.formItem.type = 'images';
                    }else if(docsArr.includes(exceededStr)){
                    	this.formItem.bucket = 'docs';
                    	this.formItem.type = 'docs';
                    }else if(othersArr.includes(exceededStr)){
                    	this.formItem.bucket = 'files';
                    	this.formItem.type = 'files';
                    }else if(videoArr.includes(exceededStr)){
                    	this.formItem.bucket = 'videos';
                    	this.formItem.type = 'videos';
                    }else if(audioArr.includes(exceededStr)){
                    	this.formItem.bucket = 'audios';
                    	this.formItem.type = 'audios';
                    }else if(exceededStr == 'glb'){
                    	this.formItem.bucket = 'relay';
                    	this.formItem.type = "glb";
                    }else{
                    	this.formItem.bucket = 'files';
                    	this.formItem.type = 'files';
                    }
                    return false;
                }else{
                    this.uploadFile = null
                    this.formItem.file = ''
                    this.formItem.bucket = '';
                    this.formItem.type = '';
                    this.$Message.error({
                        content:'不支持当前文件类型',
                        duration:3,
                    })
                    return false
                }
            },
            formBtn(name){
                let _this = this
                let isPublic = ''
                if(!this.formItem.file){
            	    _this.$Message.warning({
                        content:'请先选择文件！',
                        duration:2,
                    })
                	return;
                }
                
//              if(this.formItem.visibility === '0' || this.formItem.visibility === 0){
//                  isPublic = '?visibility=0'
//              }else{
//              	isPublic = '?visibility=1'
//              }
                this.$refs[name].validate((valid) =>{
                    if(valid){
                        this.upload(_this.formItem.file)
                      
                      
                        return 
                        // 原来的直接上传 不执行了，执行上面的分片上传
                        let formData = new window.FormData()
                        formData.append('file',_this.formItem.file);
                        let file = {
                        	name:this.onlyFileName//this.formItem.file.name
                        };
                        _this.loading = true
                        _this.axios({
                            method:'post',
                            url:`${_this.upLoadUrl}?visibility=${this.formItem.visibility}&bucket=${this.formItem.bucket}&type=${this.formItem.type}`,
                            data:formData,
                            headers:{
                                'Content-type':'multipart/form-data',
                            },
                            timeout: 30 * 60 * 1000,  // 30 分钟超时
                            onUploadProgress: progressEvent => {
                            	//解决上传过程中关闭了modal,再选择文件，会显示上次上传的进度级速度问题 
                              if((file.name && _this.onlyFileName) && file.name != _this.onlyFileName){
                                    return;
                               };
                                var complete = Math.floor(progressEvent.loaded / progressEvent.total * 100)
                                _this.progress = complete
                                function getspeed () {
                                    var aaspeed = Number(progressEvent.loaded - _this.loaded)
                                    _this.loaded = progressEvent.loaded
                                    if (aaspeed > 1024 * 1024) {
                                        _this.speed = (Math.round(aaspeed * 100 / (1024 * 1024)) / 100).toString() + 'MB/s'
                                    } else {
                                        _this.speed = (Math.round(aaspeed * 100 / 1024) / 100).toString() + 'KB/s'
                                    }
                                }
                                setInterval(getspeed(), 1000)
                            }
                        })
                            .then(res=>{
                                if(res.data.code == 1){
                                    _this.formItem.file = null
                                    if(_this.progress === 100){
                                        _this.$Message.success({
                                            content:'创建成功！',
                                            duration:2,
                                        })
                                    }
                                    setTimeout(()=>{
                                        _this.loading = false
                                        this.uploadFileModal = false
                                        this.isUpdataing = false
                                        this.uploadShow = false
                                        // this.exGroupHandleReset('formItem')
                                        //this.getFileList()
                                        this.refreshFile();
                                    },2000)
                                }else {
                                    _this.loading = false
                                    this.formItem.file = null
                                    this.speed = 0
                                    this.loaded = 0
                                    this.fileSize = 0
                                    this.progress = 0
                                    this.isUpdataing = false
                                    this.uploadShow = false
                                    _this.$Message.error({
                                        content:res.data.message,
                                        duration:3,
                                    })
                                }
                            })
                            .catch(err=>{
                                console.log(err)
                                _this.$Message.error('服务器连接失败！')
                                _this.loading = false
                            })
                    }else {
                        _this.$Message.error('请完善信息！');
                    }
                })
            },
            // 计算index
            handleProIndex(key){
                return (this.videoPage-1)*this.videoPageSize + key + 1
            },
            getSize(val) {
                let type = ''
                if(val > (1024*1024)){
                    val = val/(1024*1024)
                    type = ' MB'
                }else{
                    val = val/1024
                    type = ' KB'
                }
                val = val.toFixed(2)
                return val+''+type
            },
             // 设置可见范围
             setVisibility(val){
                let obj = {}
                let text = ''
                let color = ''
                if(val === 'company'){
                    text = '单位'
                    color = '#32CD32'
                }else  if(val === 'person'){
                    text = '个人'
                    color = '#FFA500'
                }else  if(val === 'system'){
                    text = '系统'
                    color = '#4169E1'
                }
                obj.text = text
                obj.color = color
                return obj
            },
            // 时长
            getTimes(item){
                if((item.bucket == 'videos' || item.bucket == 'audios')){
                    let mss = item.duration;
                    if(item.duration == 0){
                        return item.duration
                    }
                    let days = parseInt(mss / (1000 * 60 * 60 * 24));
                    let hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    let minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
                    let seconds = (mss % (1000 * 60)) / 1000;
                    let time = '';
                    if(hours > 0){
                        time += hours + " 时 "
                    }
                    if(minutes > 0){
                        time += minutes + " 分"
                    }
                    if(seconds > 0){
                        time += seconds + " 秒 "
                    }
                    return time
                }else{
                    return '-'
                }
            },
            // 设置知否可点击
            setIsClick(item){
                if(item.visibility === 'public' || item.hidden == 1 || (item.creator !== this.USER_ID && !this.isRootDesinger)){
                    return {'pointer-events':'none'}
                }
            },
            setDelImgSrc(item){
                if(item.visibility === 'public' || item.hidden == 1 || (item.creator !== this.USER_ID && !this.isRootDesinger)){
                    return require('../../assets/project/delNote-d.png')
                }else{
                    return require('../../assets/project/delNote-h.png')
                }
            },
            handleImage(logo){
                let src = ''
                if(logo){
                    if(logo.indexOf('Learn') > -1){
                        src = logo
                    }else {
                        src = `/Learn/${logo}`
                    }
                }else {
//                  src = this.defaultImg
                }
                return src
            },
            changeModalLoading() {
                this.updataLoading = false;
                this.$nextTick(() => {
                    this.updataLoading = true;
                });
            },
            cancelUpload(){//关闭上传给出提示
                let _this = this
                if(_this.isUpdataing){
                    _this.uploadShow = true
                    _this.changeModalLoading()
                }else{
                    this.uploadFileModal = false;
                }
            },
            YesOk(){
                this.uploadShow = false
                this.uploadFileModal = false;
                this.isUpdataing = false
            },
            NoCancel(){
                this.uploadShow = false
            },
            filterFileType(type){
            	let str;
            	switch(type){
            		case 'images':
            		    str = '图片';
            		    break;
            		case 'videos':
            		    str = '视频';
            		    break;
            		case 'docs':
            		    str = '文档';
            		    break;
            		case 'audios':
            		    str = '音频';
            		    break;
            		case 'relay':
            		    str = 'glb';
            		    break;
            		case 'toolkit':
            		    str = '工具';
            		    break;
            		case 'icon':
            		    str = '图标';
            		    break;
            		case 'files':
            		    str = '其他';
            		    break;
            		default: 
        				str = "其他";
            	}
            	return str;
            },

            upload (file) {
              if (file.size <= 0) {
                this.$Message.error({
                  content: '无效文件!',
                  duration: 3
                })
                return
              }
              console.log(file.name,111111111111);
              this.filedArr = []
              var clientId = this.generateClientId() //id
              var fileName = file.name;
              var size = file.size
              // if (file.size < 1024 * 1024 * 600) {
              // var shardSize = file.size; //如果上传的文件小于600M直接以当前文件为一个分片
              // } else {
              var shardSize = 1024 * 1024 * 50; //如果上传的文件大于600M就以50M为一个分片
              // }
              var chunks = Math.ceil(size / shardSize); //总片数
              for (var i = 0; i < chunks; ++i) {
                var start = i * shardSize; //计算每一片的起始位置
                var end = Math.min(size, start + shardSize)  //计算每一片的结束位置
                var partFile = file.slice(start, end)
                this.filedArr.push(partFile)
              };
              //上传分片请求函数
              const partUpload = async (clientId, filedArr, chunks, chunkId) => {
                try {
                  let _this = this
                  let partFile = filedArr[chunkId]
                  var form = new FormData();
                  form.append('clientId', clientId); //客户端id
                  form.append('file', partFile); // slice方法 用于切出文件的一部分
                  // form.append('fileName', fileName); // 文件名
                  // form.append('chunks', chunks); // 总片数
                  form.append('chunkId', chunkId); //当前是第几片
                  const res = await _this.axios({
                    method: 'post',
                    url: `${this.baseURL}/minio/upload/part`,
                    data: form,
                    headers: {
                      'Content-type': 'multipart/form-data',
                    },
                    timeout:0,
                    onUploadProgress: progressEvent => {
  
                      this.fileSize = this.getFileSize(file.size)
  
                      this.fileName = file.name
  
                      let hasUpload = chunkId*shardSize // 已经上传的分片 大小
                      var complete = Math.floor((hasUpload+progressEvent.loaded) / file.size * 100)
                      _this.progress = complete
                      // console.log(`第${chunkId}片，已经上传${hasUpload},当前片大小${progressEvent.loaded},文件总`,file.size)
  
                      var newTime = +new Date()
                      var DTime = (newTime - this.oldTime) / 1000
                      this.oldTime = newTime
  
                      let loadingValue = _this.loading===false?0:_this.loading
                      var aaspeed = Number(progressEvent.loaded - loadingValue) / (1024 * 1024)
                      _this.loading = progressEvent.loaded
                      if (aaspeed / DTime < 1) {
                        _this.speed = (Math.round(aaspeed / DTime * 1024 * 100) / 100).toString() + 'kB/s'
                      } else {
                        _this.speed = (Math.round(aaspeed / DTime * 100) / 100).toString() + 'MB/s'
                      }
  
                      if(_this.speed.includes('NaN') || (_this.speed+'') === '0') {
                        _this.speed ='0 kB/s'
                      }
                      
                    },
                  });
                  if (res.data.code == 1) {
                    console.log('-------chunkid-----',chunkId)
                    chunkId += 1
                    if (chunkId < this.filedArr.length) {
                      _this.loading = 0
                      this.uptedIdx += 1
                      var complete = Math.ceil(this.uptedIdx / chunks * 100)   //当前进度所占总进度的百分比
                      this.progress = complete
                      partUpload(clientId, this.filedArr, chunks, chunkId)
                    } else {
                      this.uptedIdx += 1
                      var complete = Math.ceil(this.uptedIdx / chunks * 100)   //当前进度所占总进度的百分比
                      this.progress = complete
                      if (this.progress == 100) {
                        this.setDisabled = false //打开提交和选择文件按钮权限
  
                        this.speed = 0//置空速度
                        this.uptedIdx = 0
                        this.filedArr = []
                        this.uptedIdx = 0
  
                        console.log('---分片文件上传成功!几片：',chunks)
                        this.mergeFile(clientId,fileName) //不再调用合并分片接口，创建镜像的时候tempId为随机生成的clientId
                        // this.imageFormData.tempId = clientId
                      }
                    }
                  }
                } catch (error) {
                  this.$Message.error('上传文件出错')
                  console.log(error)
                }
  
              }
              partUpload(clientId, this.filedArr, chunks, 0)
            },
            mergeFile(clientId,fileName){

           
              let url = `${this.upLoadUrl}?visibility=${this.formItem.visibility}&bucket=${this.formItem.bucket}&type=${this.formItem.type}&clientId=${clientId}&sourceName=${fileName}`
              console.log(url)
              this.axios({
                method:'post',
                url:url,
                headers:{
                  'Content-type': 'multipart/form-data'
                },
                timeout:0,
              }).then(res => {
                this.uploadComplete(res)
                this.loading = false
              }).catch((err) => {
                this.$Message.error('合并文件出错')
                console.log(err,'errerrerrerrerr')
              }).finally(() => {
                this.loading = false
              })
            },
            generateClientId () {
              var counter = 0;
              var clientId = (+new Date()).toString(32),
                  i = 0;
              for (; i < 5; i++) {
                clientId += Math.floor(Math.random() * 65535).toString(32);
              }
              return clientId + (counter++).toString(32);
            },
            getFileSize(size) {
              let fileSize;
              if(size > 1024 * 1024) {
                fileSize = (Math.round(size * 100 / (1024 * 1024)) / 100).toString() + 'MB'
              } else {
                fileSize = (Math.round(size * 100 / 1024) / 100).toString() + 'KB'
              }
              return fileSize;
            },
          uploadComplete(res){
              let _this = this
              if(res.data.code == 1){

                this.uploadFileModal = false
                if(_this.progress === 100){
                  _this.$Message.success({
                    content:'创建成功！',
                    duration:2,
                  })
                }
                setTimeout(()=>{
                  _this.formItem.file = null
                  _this.loading = false
                  
                  this.isUpdataing = false
                  this.uploadShow = false
                  // this.exGroupHandleReset('formItem')
                  //this.getFileList()
                  this.refreshFile();
                },2000)
              }else {
                _this.loading = false
                this.formItem.file = null
                this.speed = 0
                this.loaded = 0
                this.fileSize = 0
                this.progress = 0
                this.isUpdataing = false
                this.uploadShow = false
                _this.$Message.error({
                  content:res.data.message,
                  duration:3,
                })
              }
            }
        }
    }
</script>
<style scoped>
    
.too{
        position: absolute;
        left: 113px;
        top: -1px;
    }
    .ios-alert{   
        /* position: absolute;
        top: -44px;
        right: -404px; */
        color: orange;
        font-size: 16px;
        cursor: pointer;
    }
    .page-wrap{
        padding: 30px;
        height: 100%;
    }
    .page-content{
        background-color: #fff;
        border-radius: 10px;
        height: 100%;
    }
    .img-header{
        display: flex;
        justify-content: space-between;
        padding: 20px 20px 0 20px;
    }
    /* 新样式 */
	.content-wrap{
		max-height: calc(100vh - 197px);
        width: 100%;
        font-size: 14px;
        overflow-x: hidden;
        overflow-y: auto;
		margin-top: 20px;
        padding: 0 20px;
    }
    .content-wrap::-webkit-scrollbar{
        /*滚动条整体样式*/
        width: 8px; /*高宽分别对应横竖滚动条的尺寸*/
        height: 4px;
    }
    .content-wrap::-webkit-scrollbar-thumb {
        /*滚动条里面小方块样式*/
        border-radius: 5px;
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: rgba(209, 209, 209,0.6);
    }
    .content-wrap::-webkit-scrollbar-track{
        /*滚动条里面轨道样式*/
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 5px;
        background: rgba(179, 179, 179, 0.1);
    }
    .project-item{
        width: 100%;
        border-radius: 4px;
        border: 2px solid rgb(231, 231, 241);
        padding: 10px 15px;
        margin-bottom: 15px;
    }
    .item-first-line{
        display: flex;
        justify-content: space-between;
    }
    .project-name-state{
        display: flex;
        justify-content: flex-start;
    }
    .project-name{
        font-size: 16px;
        font-weight: 600;
        max-width: 400px;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
    }
    .project-status-text{
        font-weight: 600;
        font-size: 14px;
        margin-left: 10px;
		display: flex;
		justify-content: flex-start;
    }
    .btn-icon-wrap{
        display: flex;
        justify-content: flex-end;
    }
    .click-icon{
        cursor: pointer;
        height: 22px;
        margin-left: 20px;
    }
    .click-icon-disabled {
        cursor: not-allowed;
    }
    .project-other-info{
        display: flex;
        justify-content: flex-start;
        margin-top: 8px;
        color: rgba(51, 51, 51,0.4);
        font-weight: bold;
    }
	.sendMsgContent{
		display: flex;
		justify-content: flex-start;
		margin-left: 15px;
		white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
		width: calc(100vh - 300px);
	}
	/* 省略图 */
    .defGraphWrap{
        width: 100%;
        height: calc(100vh - 120px);
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }
    .defGraph{
        height: 126px;
        width: 157px;
        background: url("../../assets/globalIcon/defGraph.png") no-repeat center center;
        background-size: 157px 126px;
    }
    .graphText{
        color: #888;
        font-size: 14px;
        text-align: center;
        margin-top: 20px;
    }
    .thumbnails{
    	display: inline-block;
    	max-height: 30px;
    	width: auto;
    	margin-left: 20px;
    	vertical-align: middle;
    }
    .uploadTypeWrap{
        color: orange;
        margin-bottom: 16px;
    }
    .uploadTypeWrap /deep/ .ivu-tooltip-inner{
        word-break: break-all;
        white-space: pre-wrap;
    }
</style>
<style>
.tooltipclass .ivu-poptip-inner{
         background-color: rgba(70,76,91,.9);
         color:#fff;
    }
    .tooltipclass.ivu-poptip-popper[x-placement^=top] .ivu-poptip-arrow:after{
        border-top-color:rgba(70,76,91,.9);
    }
    .tooltipclass.ivu-poptip-popper[x-placement^=bottom] .ivu-poptip-arrow:after{
        border-bottom-color:rgba(70,76,91,.9);
    }
</style>